package org.easy.http.client.http;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import org.easy.http.client.util.IoUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description TODO
 * @Author WuXueLi
 * @Date 19:29 2023/2/25
 * @Version 1.0
 **/
public class InputStreamRequestBody extends RequestBody {

    private final byte[] content;

    private final int byteCount;

    private final MediaType mediaType;

    public InputStreamRequestBody (InputStream stream,MediaType mediaType) {
        this.mediaType = mediaType;
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        try {
            IoUtils.copy(stream,b);
            this.content = b.toByteArray();
            this.byteCount = this.content.length;
        } finally {
            IoUtils.closeQuietly(stream);
        }

    }

    @Override
    public long contentLength() throws IOException {
        return this.byteCount;
    }

    @Override
    public MediaType contentType() {
        return this.mediaType;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        sink.write(this.content,0,this.byteCount);
    }
}
